<template>
  <view class="bg"></view>
  <view class="wrapper">
    <image class="build-img" src="/pageAuth/static/2.png"></image>
    <image class="yunbao-img" src="/pageAuth/static/4.png"></image>
    <view class="bg-2"></view>
    <view class="bg-1"></view>
    <view
      class="bg-ffffff absolute top-0 left-0 wp-100 hp-100 border-radius-24 column align-center"
    >
      <image class="w-360 h-100 mt-80" src="/pageAuth/static/6.png"></image>
      <view class="fs-40 cl-1e262f mt-48">欢迎进行身份认证</view>
      <image class="yunbao-shou-img" src="/pageAuth/static/5.png"></image>
      <view class="pl-48 pr-48 wp-100 mt-64">
        <view class="pb-8 bb-828282 row align-center mt-24">
          <input
            class="h-80 lh-80 fs-32"
            v-model="personInfo.mobile"
            placeholder="请输入手机号"
            disabled
            :maxlength="11"
            type="name"
          />
          <view class="cl-408af7 fs-32 w-160 text-center" @tap="getCode()">
            {{ countTime < 60 ? countTime + 's' : '获取验证码' }}
          </view>
        </view>

        <input
          class="h-80 lh-80 pb-8 bb-828282 fs-32 mt-24 wp-100"
          v-model="personInfo.code"
          placeholder="请输入验证码"
          :maxlength="6"
        />
        <view class="pl-48 pr-48 wp-100">
          <button @tap="verifyMobile()" class="wx-btn" :loading="logining">
            立即认证
          </button>
          <!-- <view
            class="btn-auth fw-bold"
            @tap="verifyMobile()"
          >
            立即认证
          </view> -->
        </view>
      </view>
    </view>
  </view>
</template>
<script lang="ts" setup>
  import { useClearLoginChannelRelations } from '@/hooks/hooks'
  import { computed, ref, Ref } from 'vue'
  import { useStore } from 'vuex'
  import { throttle } from '@/utils/common'
  import { msg } from '@/utils/tools'
  import uma from '@/utils/uma'
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import { accountUserInfo, alipayMiniBind, sendSMS } from '@/api/login'
  import { GET_TIME_DOWN, THREE_PART_LOGIN_DATA } from '@/utils/storageTypes'
  import { SET_TGT_TOKEN, SET_USER_INFO } from '@/store/types'
  import { uploadUserInfo } from '@/api/auth'

  const store = useStore()
  const commit = store.commit
  const personInfo: Ref<{
    mobile: string
    openId: string
    code: string
    userId: string
  }> = ref({
    mobile: '',
    openId: '',
    code: '',
    userId: '',
  })

  onLoad((options) => {
    personInfo.value = options as typeof personInfo.value
    personInfo.value.mobile = options.phone || ''
    if (countTime.value !== 60) {
      countdown()
    }
  })

  onUnload(() => {
    if (!tgt.value) {
      useClearLoginChannelRelations()
    }
  })
  const logining = ref(false)
  const tgt = computed(() => store.state.user.TGT)
  const timeDown = {
    getTimeDown(): number | undefined {
      return uni.getStorageSync(GET_TIME_DOWN)
    },
    setTimeDown() {
      return uni.setStorageSync(GET_TIME_DOWN, countTime.value)
    },
  }

  let countTime = ref(timeDown.getTimeDown() || 60)

  // 获取验证码
  const getCode = throttle(async function () {
    if (countTime.value < 60) {
      return
    }
    try {
      const { data, code } = await sendSMS({
        mobile: personInfo.value.mobile,
      })

      if (+code !== 200) return

      countdown()
    } catch (e) {
      //TODO handle the exception
      console.log(e)
      countTime.value = 60
      timeDown.setTimeDown()
      clearTimeout(timer)
    }
  }, 2000)

  // 倒计时
  let timer = 0
  function countdown() {
    if (+countTime.value === 0) {
      countTime.value = 60
      timeDown.setTimeDown()
      return clearTimeout(timer)
    }
    timer = setTimeout(() => {
      countTime.value--
      timeDown.setTimeDown()
      countdown()
    }, 1000)
  }

  async function verifyMobile() {
    if (!personInfo.value.code) {
      return msg('请输入验证码')
    }
    logining.value = true
    try {
      const { code, data } = await alipayMiniBind(personInfo.value)
      if (data.tgt) {
        commit(`user/${SET_TGT_TOKEN}`, data.tgt)
        uni.setStorageSync(THREE_PART_LOGIN_DATA, data)
        getUserInfoFromAccountSys(data.tgt)
      }
      logining.value = false
    } catch (e) {
      logining.value = false
      //TODO handle the exception
    }
  }

  // 获取账号系统用户信息 重组 微信用户信息
  const getUserInfoFromAccountSys = async (tgt: string) => {
    try {
      const { data, code, msg: message } = await accountUserInfo(tgt)
      if (code !== 200) {
        return msg('用户信息获取失败:' + message)
      }

      uni.setStorageSync('userInfo', { ...data })
      commit(`user/${SET_USER_INFO}`, { ...data })
      // bindAccountSys()
      await upload({
        tgt: uni.getStorageSync(THREE_PART_LOGIN_DATA)?.tgt || '',
        aid: data.aid,
        userDTO: data,
        // code: result.code,
      })

      uni.navigateBack({})
    } catch (e) {
      msg('用户信息获取失败，请稍后重试')
      console.log('用户信息获取失败', e)
    }
  }

  const upload = async (data: {
    aid: string
    tgt: string
    userDTO: AnyObject
    // code?: string
  }) => {
    try {
      await uploadUserInfo(data)
    } catch (e) {
      msg('上传登录信息失败，请卸载小程序后重新登录')
      //TODO handle the exception
    }
    return Promise.resolve()
  }
</script>
<style lang="scss" scoped>
  .btn-auth {
    margin-top: 11.2068vh;
    width: 100%;
    height: 88rpx;
    background-image: linear-gradient(-45deg, #75befc 0%, #408af7 100%);
    box-shadow: 0 8rpx 16rpx 0 rgba(64, 138, 247, 0.3);
    border-radius: 44rpx;
    line-height: 88rpx;
    text-align: center;
    color: #ffffff;
    font-size: 30rpx;
  }
  .bb-828282 {
    border-bottom: 1rpx solid rgba(130, 130, 130, 0.2);
  }
  .bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-image: linear-gradient(180deg, #0c82ea 0%, #92c2ff 100%);
  }

  .border-radius-24 {
    border-radius: 24rpx;
  }

  .wrapper {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 670rpx;
    height: calc(1104 * 100 / 1624 * 1vh);
    background: #ffffff;
    border-radius: 24rpx;
    .build-img {
      position: absolute;
      top: -200rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 590rpx;
      height: 338rpx;
      animation: scale ease-in 1.5s 1;
    }
    .yunbao-img {
      position: absolute;
      top: -200rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 240rpx;
      height: 240rpx;
    }

    .yunbao-shou-img {
      position: absolute;
      top: -13rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 160rpx;
      height: 40rpx;
    }
    .wx-btn {
      margin-top: 240rpx;
      width: 100%;
      height: 88rpx;
      background-image: linear-gradient(-45deg, #75befc 0%, #408af7 100%);
      box-shadow: 0 8rpx 16rpx 0 rgba(64, 138, 247, 0.3);
      border-radius: 44rpx;
      border: none;
      font-weight: 500;
      font-size: 30rpx;
      color: #ffffff;
      text-align: center;
    }

    .m-protocal {
      .btn {
        background: #e0dfdf;
        transition: all 0.3s linear;
        &.active {
          background: #408af7;
        }
      }
    }
  }

  @each $var in 360 40 32 {
    .w-#{$var} {
      width: $var * 1rpx;
    }

    .border-radius-#{$var} {
      border-radius: $var * 1rpx;
    }
  }

  .txt-6 {
    color: rgba(30, 38, 47, 0.6);
  }

  .bg-1 {
    position: absolute;
    top: 230rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 606rpx;
    height: calc(906 * 100 / 1624 * 1vh);
    opacity: 0.6;
    background: #ffffff;
    border-radius: 24rpx;
    animation: move1 linear 1.5s 1;
  }

  .bg-2 {
    position: absolute;
    top: 262rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 542rpx;
    height: calc(906 * 100 / 1624 * 1vh);
    opacity: 0.2;
    background: #ffffff;
    border-radius: 24rpx;
    animation: move2 linear 2s 1;
  }

  @keyframes move1 {
    0% {
      top: 0;
    }

    85% {
      top: 262rpx;
    }
    100% {
      top: 230rpx;
    }
  }

  @keyframes move2 {
    0% {
      top: 0;
    }
    85% {
      top: 292rpx;
    }
    100% {
      top: 262rpx;
    }
  }

  @keyframes scale {
    0% {
      transform: translateX(-50%) scale(0.5);
    }
    100% {
      transform: translateX(-50%) scale(1);
    }
  }
</style>
